package com.framework.helper;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.framework.annotation.RequestMapping;
import com.framework.bean.Handler;
import com.framework.bean.Request;
import com.framework.util.ArrayUtil;
import com.framework.util.CollectionUtil;


/**
 * 控制器助手类
 * @author ckm
 *
 */
public class ControllerHelper {

    private static final Map<Request, Handler> ACTION_MAP = new HashMap<Request, Handler>();

    static {
        Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
        if (CollectionUtil.isNotEmpty(controllerClassSet)) {
            for (Class<?> controllerClass : controllerClassSet) {
                Method[] methods = controllerClass.getDeclaredMethods();
                if (ArrayUtil.isNotEmpty(methods)) {
                    for (Method method : methods) {
                    	// 判断方法上是否包含 Action
                        if (method.isAnnotationPresent(RequestMapping.class)) {
                        	// 获取注解上的 请求路径 和 方式
                            RequestMapping action = method.getAnnotation(RequestMapping.class);
                            String requestPath = action.value();
                            String requestMethod = action.method().toString();
                            Request request = new Request(requestMethod, requestPath);
                            Handler handler = new Handler(controllerClass, method);
                            ACTION_MAP.put(request, handler);
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取 Handler
     */
    public static Handler getHandler(String requestMethod, String requestPath) {
        Request request = new Request(requestMethod, requestPath);
        return ACTION_MAP.get(request);
    }
}
